using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Xml;
using System.Collections.Specialized;
namespace BlogControl
{
    [ToolboxData("<{0}:Blog runat=server></{0}:Blog>")]
    [Designer(typeof(BlogDesigner))]
    public partial class Blog : WebControl, INamingContainer
    {
        public Blog() : base(HtmlTextWriterTag.Div) { }
        private StringBuilder _buffer;
        public StringBuilder Buffer
        {
            get
            {
                if (_buffer == null)
                {
                    _buffer = new StringBuilder();
                }
                return _buffer;
            }
        }
        public int addPostButtonIndex=-1;
        public int newPostTitleIndex = -1;

        public int newPostBodyIndex = -1;
        public int newPostSubmitIndex = -1;
        public int newPostCancelIndex = -1;
        public int addCommentButtonIndex = -1;
        public int newPostWriterIndex = -1;
        public int calendarIndex = -1;
        public int showFullPostIndex = -1;
        public int addCommentSubmitButtonIndex = -1;
        public int[] pagingIndexes;
        //protected override void Render(HtmlTextWriter writer)
        //{
        //    writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
        //    writer.RenderBeginTag(HtmlTextWriterTag.Div);
        //    RenderContents(writer);
        //    writer.RenderEndTag();
        //}
        protected override void CreateChildControls()
        {
            if (AllowPaging)
            {
                int pagesCount =(int) Math.Ceiling((double)FilesCount /(double) PostsPerPage);
                pagingIndexes = new int[pagesCount];
                for (int i = 0; i < pagesCount; i++)
                {
                    LinkButton lb = new LinkButton();
                    lb.ID = "pager" + i;
                    lb.Click += new EventHandler(lbPager_Click);
                    Controls.Add(lb);
                    pagingIndexes[i] = Controls.Count - 1;
                }
            }
            
            if (ShowAddPostButton)
            {
                Button bt = new Button();
                bt.ID = "btnAddPost";
                bt.Click += new EventHandler(btAddPost_Click);
                bt.Text = AddPostButtonText;
                Controls.Add(bt);
                addPostButtonIndex = Controls.Count - 1;
            }
            TextBox txt = new TextBox();
            txt.ID = "txtNewPostTitle";
            Controls.Add(txt);
            newPostTitleIndex = Controls.Count - 1;

           
                FreeTextBoxControls.FreeTextBox htmlEditor = new FreeTextBoxControls.FreeTextBox();
                htmlEditor.ID = "txtNewPostBody";
                Controls.Add(htmlEditor);                
                newPostBodyIndex = Controls.Count - 1;
          
            if (AllowSinglePostView)
            {
                LinkButton lbShowSinglePost = new LinkButton();
                lbShowSinglePost.Click += new EventHandler(lbShowSinglePost_Click);
                Controls.Add(lbShowSinglePost);
                showFullPostIndex = Controls.Count - 1;
            }

            Button addCommentSubmitButton = new Button();
            addCommentSubmitButton.Click += new EventHandler(addCommentSubmitButton_Click);
            Controls.Add(addCommentSubmitButton);
            addCommentSubmitButtonIndex = Controls.Count - 1;

            txt = new TextBox();
            txt.ID = "txtNewPostWriter";
            Controls.Add(txt);
            newPostWriterIndex = Controls.Count - 1;

            Button newPostSubmit = new Button();
            newPostSubmit.Click += new EventHandler(newPostSubmit_Click);
            newPostSubmit.Text = this.AddPostSubmitText;
            Controls.Add(newPostSubmit);
            newPostSubmitIndex = Controls.Count - 1;

            Button newPostCancel = new Button();
            newPostCancel.OnClientClick = "javascript:setCurrentAction('" + ActionType.Default + "')";
            newPostCancel.Text = this.AddPostCancelText;
            newPostCancel.Click += new EventHandler(newPostCancel_Click);
            Controls.Add(newPostCancel);
            newPostCancelIndex = Controls.Count - 1;

            Button addComment = new Button();
            addComment.Text = this.AddCommentSubjectText;
            addComment.Click += new EventHandler(addComment_Click);
            addComment.ID = "AddComment";
            Controls.Add(addComment);
            addCommentButtonIndex = Controls.Count - 1;
        }

        void addCommentSubmitButton_Click(object sender, EventArgs e)
        {
            CurrentAction = ActionType.AddComment;
        }

        void lbShowSinglePost_Click(object sender, EventArgs e)
        {
            _currentAction = ActionType.ViewPost;
        }

       
        
        void lbPager_Click(object sender, EventArgs e)
        {
            _currentAction = ActionType.Default;
            this.PageIndex = Convert.ToInt32(((LinkButton)sender).ID.Substring(5));
            int lastPageIndex = JavascriptManager.GetLastPageIndex();
            if (lastPageIndex != this.PageIndex)
            {
                TriggerPageIndexChanged(new PageIndexChangedArguments(this.PageIndex, lastPageIndex));
            }
        }

        void addComment_Click(object sender, EventArgs e)
        {
            this._currentAction = ActionType.AddComment;
            this.CommandArgument = ((Button)sender).CommandArgument;
        }

        void newPostCancel_Click(object sender, EventArgs e)
        {
            this._currentAction = ActionType.Default;
        }

        void newPostSubmit_Click(object sender, EventArgs e)
        {
            this._currentAction = ActionType.AddNewPost;
        }
        [Browsable(false)]
        public bool IsDesignMode
        {
            get { return this.DesignMode; }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (DrawExternalCalendar)
            {
                Archives.RenderCalendar(CalendarID);
            }
        }
        private ArchiveManager _archives;
        private ArchiveManager Archives
        {
            get
            {
                if (_archives == null)
                {
                    _archives = new ArchiveManager(this);
                }
                return _archives;
            }
        }
        protected override void RenderContents(HtmlTextWriter output)
        {
            if (this.DesignMode)
            {
                new PostsView(output, this).RenderPostsView();
                return;
            }
            if (this.Visible && this.Directory!=null)
            {
               
                CheckHiddenActions();
               
                switch (CurrentAction)
                {
                    case ActionType.Default:
                        new PostsView(output,this).RenderPostsView();
                        break;
                    case ActionType.ShowAddNewPost:
                        AddNewPost.RenderNewPostForm(this, output);
                        break;
                    case ActionType.AddNewPost:
                        AddNewPost.SaveNewPost(this, output);
                        break;
                    case ActionType.AddComment:
                        CommentsManager.AddComment(this, output);
                        new PostsView(output, this).RenderPostsView();
                        JavascriptManager.WriteAllFunctions(output);
                        break;
                    case ActionType.ViewPost:
                        new PostsView(output,this).RenderSinglePostView();
                        break;
                }
                JavascriptManager.WriteAllFunctions(output);
                if (_buffer != null)
                {
                    output.Write(_buffer.ToString());
                }
            }
            
        }
        StringCollection _postsDates;
        [Browsable(false)]
        internal StringCollection PostsDates
        {
            get
            {
                if (_postsDates == null)
                {
                    _postsDates = new StringCollection();
                    int j = Files.Length;//make sure files have been loaded
                }
                return _postsDates;
            }
        }

        private string _datesFilter;

        public string DatesFilter
        {
            get
            {
                if (_datesFilter == null)
                {
                    string s = Archives.GetDatesFilter(this);
                    if (s == null)
                        _datesFilter = string.Empty;
                    else
                        _datesFilter = s;
                }
                return _datesFilter;
            }
           
        }


        private string[] _files;
        [Browsable(false)]
        public string[] Files
        {
            get
            {
                if (this.DesignMode)
                {
                    return new string[7];
                }
                if (_files == null)
                {
                    _files = FilesManager.LoadFilesNames(this,Directory);
                }
                return _files;
            }
        }
        /// <summary>
        /// the number of posts we have
        /// </summary>
        internal int FilesCount
        {
            get
            {
                return Files.Length;
            }
        }

        private void CheckHiddenActions()
        {

            if (this.DesignMode) return;
            if (!this.Page.IsPostBack && !string.IsNullOrEmpty(HttpContext.Current.Request.Params["postId"]))
            {//first entrance and we have the permalink values
                _currentAction = ActionType.ViewPost;
                CommandArgument = HttpContext.Current.Request.Params["postId"];
            }

            if (!string.IsNullOrEmpty(HttpContext.Current.Request.Params["hiddenActionName"]))
            {
                _currentAction = (ActionType)Enum.Parse(typeof(ActionType), HttpContext.Current.Request.Params["hiddenActionName"]);
            }
           
            if (!string.IsNullOrEmpty(HttpContext.Current.Request.Params["hiddenPostId"]))
            {
                CommandArgument = HttpContext.Current.Request.Params["hiddenPostId"];
            }
            
            if (!string.IsNullOrEmpty(HttpContext.Current.Request.Params["nextPageIndex"]))
            {
                int lastPageIndex = JavascriptManager.GetLastPageIndex();
                this.PageIndex = Convert.ToInt32(HttpContext.Current.Request.Params["nextPageIndex"]);
                if (lastPageIndex != this.PageIndex)
                {
                    TriggerPageIndexChanged(new PageIndexChangedArguments(this.PageIndex, lastPageIndex));
                }
            }
            JavascriptManager.SetOldPageIndex(this.Buffer,this.PageIndex);
            if (!_currentAction.HasValue && !string.IsNullOrEmpty(HttpContext.Current.Request.Params["postId"]))
            {//no action was found and have permalink values
                _currentAction = ActionType.ViewPost;
                CommandArgument = HttpContext.Current.Request.Params["postId"];
            }
            if (!_currentAction.HasValue) _currentAction = ActionType.Default;
        }
        private string _commandArgument;
        [Browsable(false)]
        public string CommandArgument
        {
            get
            {
                
                return this._commandArgument;
            }
            set { this._commandArgument = value; }
        }
        [Browsable(false)]
        public ActionType CurrentAction
        {
            get
            {
                if (this.IsDesignMode) return ActionType.Default;
                return _currentAction.Value;

            }
            set
            {
                _currentAction = value;
            }
                
        }
       

        private ActionType? _currentAction;

        public enum ActionType
        {
            Default, ShowAddNewPost, AddNewPost, AddComment, ViewPost
        }
        void btAddPost_Click(object sender, EventArgs e)
        {
            CurrentAction = ActionType.ShowAddNewPost;
            
        }

     
    }
}
